package com.dog.basics.mqtt.config;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import javax.annotation.Resource;


/**
 * @author DreamChan
 * @Description: mqtt 配置
 * @date 19/1/2020
 */
@Slf4j
@Configuration
@IntegrationComponentScan
public class MqttConfig {

    /**
     * 订阅的bean名称
     */
    public static final String CHANNEL_NAME_IN = "mqttInboundChannel";
    /**
     * 发布的bean名称
     */
    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";
    private static final byte[] WILL_DATA;

    static {
        WILL_DATA = "offline".getBytes();
    }

    @Resource
    private MqttEntity mqttEntity;

    /**
     * 声明的接收名字必须与项目中生成的一样
     */
    @Resource
    private  MessageHandler mqttMessageReceiver;

    /**
     * mqtt 连接配置
     *
     * @return
     */
    public MqttConnectOptions getMqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
        // 这里设置为true表示每次连接到服务器都以新的身份连接
        mqttConnectOptions.setCleanSession(false);
        // MQTT 重连机制
        mqttConnectOptions.setAutomaticReconnect(Boolean.TRUE);
        // 设置连接的用户名
        mqttConnectOptions.setUserName(mqttEntity.getUsername());
        // 设置连接的密码
        mqttConnectOptions.setPassword(mqttEntity.getPassword().toCharArray());
        // 设置连接mqtt服务器地址
        mqttConnectOptions.setServerURIs(mqttEntity.getUrl().split(","));
        // 设置超时时间 单位为秒
        mqttConnectOptions.setConnectionTimeout(30);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线，但这个方法并没有重连的机制
        mqttConnectOptions.setKeepAliveInterval(60);
        // 设置“遗嘱”消息的话题，若客户端与服务器之间的连接意外中断，服务器将发布客户端的“遗嘱”消息
        mqttConnectOptions.setWill("willTopic", WILL_DATA, 2, false);
        return mqttConnectOptions;
    }

    /**
     * mqtt 客户端
     *
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory defaultMqttPahoClientFactory = new DefaultMqttPahoClientFactory();
        defaultMqttPahoClientFactory.setConnectionOptions(getMqttConnectOptions());
        return defaultMqttPahoClientFactory;
    }

    /**
     * MQTT信息通道（生产者）
     *
     * @return
     */
    @Bean(name = CHANNEL_NAME_OUT)
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * MQTT消息处理器（生产者）
     *
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
                mqttEntity.getProducerClientId(),
                mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(mqttEntity.getProducerDefaultTopic());
        return messageHandler;
    }

    /**
     * MQTT消息订阅绑定
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "mqtt",name = "isInbound",havingValue = "true")
    public MessageProducer inbound() {
        // 可以同时消费（订阅）多个Topic
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                mqttEntity.getConsumerClientId(), mqttClientFactory(),
                mqttEntity.getConsumerDefaultTopic().split(","));

        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        // 设置订阅通道
        adapter.setOutputChannel(mqttInBoundChannel());
        // 设置转换器，接收bytes 【暂不使用】
/*
        DefaultPahoMessageConverter converter = new DefaultPahoMessageConverter();
        converter.setPayloadAsBytes(true);
        adapter.setConverter(converter);*/
        return adapter;
    }

    /**
     * MQTT信息通道（消费者）
     *
     * @return
     */
    @Bean(name = CHANNEL_NAME_IN)
    @ConditionalOnProperty(prefix = "mqtt",name = "isInbound",havingValue = "true")
    public MessageChannel mqttInBoundChannel() {
        return new DirectChannel();
    }


    /**
     * MQTT消息处理器（消费者） 订阅的消息将会在这里打印
     *
     * @return {@link org.springframework.messaging.MessageHandler}
     */
    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_IN)
    public MessageHandler handler() {
        return this.mqttMessageReceiver;
    }

}
